package com.bdqn.membersystem.controller;

import com.alibaba.fastjson.JSONObject;
import com.bdqn.membersystem.common.HtmlEncode;
import com.bdqn.membersystem.common.PageUtils;
import com.bdqn.membersystem.pojo.Affiche;
import com.bdqn.membersystem.common.Constants;
import com.bdqn.membersystem.pojo.AuUser;
import com.bdqn.membersystem.pojo.Information;
import com.bdqn.membersystem.service.AfficheService;
import lombok.extern.log4j.Log4j;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

/**
 * @PackgeName: com.bdqn.membersystem.controller
 * @ClassName: AfficheController
 * @Author: 汤武琪
 * Date: 2020/4/16 10:57
 * project name: menber-system
 * @Version:
 * @Description:公告管理控制器
 */
@Controller
@Log4j
public class AfficheController extends BaseController{

    @Resource
    private AfficheService afficheService;

    /**
     * 首页公告列表
     * @param session
     * @param model
     * @param p
     * @return
     */
    @RequestMapping("/informanage/portalafficheList.html")
    public ModelAndView afficheList(HttpSession session,Model model,@RequestParam(value="p",required=false)Integer p){
        Map<String,Object> baseModel= (Map<String,Object>)session.getAttribute(Constants.SESSION_BASE_MODEL);
        List<Information> informationList = null;
        if(baseModel == null){
            return new ModelAndView("redirect:/");
        }else{
            affiche(session,model,p,true);
        }
        return new ModelAndView("informanage/portalaffichelist");
    }

    /**
     *公告管理 跳转至公告列表页
     * @param session
     * @param model
     * @param p 当前页
     * @param isPortal
     * @return
     */
    @RequestMapping("/informanage/affiche.html")
    public ModelAndView affiche(HttpSession session,Model model,@RequestParam(value="p",required=false)Integer p,boolean isPortal){
        Map<String,Object> baseModel= (Map<String,Object>)session.getAttribute(Constants.SESSION_BASE_MODEL);
        List<Affiche> afficheList = null;
        if(baseModel == null){
            return new ModelAndView("redirect:/");
        }else{
            Affiche affiche = new Affiche();
            //pages
            PageUtils page = new PageUtils();
            try{
                if(isPortal){
                    page.setTotalCount(afficheService.portalCount());
                }else{
                    page.setTotalCount(afficheService.count());
                }
            }catch (Exception e1) {
                page.setTotalCount(0);
            }
            if(page.getTotalCount() > 0){
                if(p != null){
                    page.setPage(p);}
                if(page.getPage() <= 0){
                    page.setPage(1);}
                if(page.getPage() > page.getPageCount()){
                    page.setPage(page.getPageCount());}

                affiche.setStartNum((page.getPage() - 1) * page.getPageSize());
                affiche.setPageSize(page.getPageSize());

                try {
                    if(isPortal){
                        afficheList = afficheService.getPortalAfficheList(affiche);
                    }else{
                        afficheList = afficheService.getAfficheList(affiche);
                    }

                }catch (Exception e) {
                    e.printStackTrace();
                    afficheList = null;
                    if(page == null){
                        page = new PageUtils();
                        page.setItems(null);
                    }
                }
                page.setItems(afficheList);
            }else{
                page.setItems(null);
            }
            model.addAllAttributes(baseModel);
            model.addAttribute("page", page);
        }
        return new ModelAndView("informanage/affiche");
    }

    /**
     * 首页公告详情
     * @param session
     * @param id
     * @param model
     * @return
     */
    @RequestMapping("/informanage/portalAfficheDetail.html")
    public ModelAndView viewAffiche(HttpSession session,@RequestParam Integer id,Model model) {
        Map<String, Object> baseModel = (Map<String, Object>) session.getAttribute(Constants.SESSION_BASE_MODEL);
        if (baseModel == null) {
            return new ModelAndView("redirect:/");
        } else {
            if (null == id || "".equals(id)) {
                id = 0;
            } else {
                try {
                    Affiche affiche = new Affiche();
                    affiche.setId(Long.valueOf(id));
                    affiche = afficheService.getAffiche(affiche);
                    if (null != affiche && affiche.getCode() != null) {
                        model.addAttribute("affiche", affiche);
                    }
                } catch (Exception e) {
                }
            }
        }
        model.addAllAttributes(baseModel);
        return new ModelAndView("informanage/portalaffichedetail");
    }

    /**
     *
     * 查看公告按钮
     * @param session
     * @param id
     * @return
     */
    @PostMapping(value="/informanage/viewAffiche.html", produces = {"text/html;charset=UTF-8"})
    @ResponseBody
    public Object viewAffiche(HttpSession session,@RequestParam Integer id){
        String result = "";
        if(null == id || "".equals(id)){
            result =  "nodata";
        }else{
            try {
                Affiche affiche = new Affiche();
                affiche.setId(Long.valueOf(id));
                affiche = afficheService.getAffiche(affiche);
                if(null != affiche && affiche.getCode() != null && affiche.getTitle() != null){
                    affiche.setTitle(HtmlEncode.htmlDecode(affiche.getTitle()));
                    result = affiche.toString();
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                result =  "failed";
            }
        }
        log.info(result);
        return result;
    }

    /**
     * 修改公告
     * @param affiche
     * @param session
     * @return
     */
    @RequestMapping(value="/informanage/modifyAffiche.html",method=RequestMethod.POST)
    public ModelAndView modifyAffiche(@ModelAttribute("addAffiche") Affiche affiche,HttpSession session){
        if(session.getAttribute(Constants.SESSION_BASE_MODEL) == null){
            return new ModelAndView("redirect:/");
        }else{
            try {
                AuUser sessionUser =  ((AuUser)session.getAttribute(Constants.SESSION_USER));
                affiche.setPublisher(sessionUser.getLoginCode());
                affiche.setPublishTime(new Date(System.currentTimeMillis()));
                if(null != affiche.getTitle() && !affiche.getTitle().equals("")){
                    affiche.setTitle(HtmlEncode.htmlEncode(affiche.getTitle()));
                }
                afficheService.modifyAffiche(affiche);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        return new ModelAndView("redirect:/informanage/affiche.html");
    }

    /**
     * 删除公告
     * @param session
     * @param id
     * @return
     */
    @RequestMapping("/informanage/delAffiche.html")
    @ResponseBody
    public Object delAffiche(HttpSession session,@RequestParam Integer id) {

        if (null == id || "".equals(id)) {
            return "nodata";
        } else {
            try {
                Affiche affiche = new Affiche();
                affiche.setId(Long.valueOf(id));
                afficheService.deleteAffiche(affiche);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                return "failed";
            }
            return "success";
        }
    }

    /**
     * 新增公告
     * @param addAffiche
     * @param session
     * @return
     */
        @RequestMapping(value="/informanage/addAffiche.html",method= RequestMethod.POST)
        public ModelAndView addAffiche(@ModelAttribute("addAffiche") Affiche addAffiche, HttpSession session, MultipartHttpServletRequest request){
            if(session.getAttribute(Constants.SESSION_BASE_MODEL) == null){
                return new ModelAndView("redirect:/");
            }else{
                try {
                    Map<String,String[]> parameterMap = request.getParameterMap();
                    Map<String, Object> map = new HashMap<>(parameterMap.size());
                    for (String key:parameterMap.keySet()){
                        map.put(key,parameterMap.get(key)[0]);
                    }
//                    addAffiche = JSONObject.toJavaObject(map);
                    AuUser sessionUser =  ((AuUser)session.getAttribute(Constants.SESSION_USER));
                    addAffiche.setPublisher(sessionUser.getLoginCode());
                    addAffiche.setPublishTime(new Date(System.currentTimeMillis()));
                    if(null != addAffiche.getTitle() && !addAffiche.getTitle().equals("")){
                        addAffiche.setTitle(HtmlEncode.htmlEncode(addAffiche.getTitle()));
                    }
                    afficheService.addAffiche(addAffiche);
                } catch (Exception e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
            return new ModelAndView("redirect:/informanage/affiche.html");
        }




}
